package com.huiminpay.merchant.handler;

import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.ErrorCode;
import com.huiminpay.common.cache.domain.RestErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局异常捕获类
 */
@ControllerAdvice
@Slf4j
public class GlobaExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse processException(Exception e){
        log.error(e.getMessage());
        //判断异常为自定义异常还是未知异常
        //已知异常
        if(e instanceof BusinessException){
            BusinessException businessException=(BusinessException)e;
            ErrorCode errorCode=businessException.getErrorCode();
            return  new RestErrorResponse(errorCode.getCode(),errorCode.getDesc());
        }
        //未知异常
         return  new RestErrorResponse(CommonErrorCode.UNKOWN.getCode(),CommonErrorCode.UNKOWN.getDesc());
    }
}
